package com.loren.service.impl;

import com.loren.config.DynamicDataSourceHolder;
import com.loren.constant.DataSourceContant;
import com.loren.entity.Person;
import com.loren.repository.DbInfoRepository;
import com.loren.repository.PersonRepository;
import com.loren.service.PersonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class PersonServiceImpl implements PersonService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PersonRepository personRepository;

    @Autowired
    private DbInfoRepository dbInfoRepository;

    @Override
    public Person getPersonInfo() {
//        切换到Person表所在的数据源
        DynamicDataSourceHolder.setDataSourceType(String.valueOf(DataSourceContant.PERSON_DATASOURCE_ID));
        return this.personRepository.findById(1).orElse(null);
    }

    @Override
    public Map<String, Object> getMultipleDataSourceInfo() {

        Map<String, Object> resultMap = new HashMap<>();

        logger.info("=====操作Person所在的数据库=====");
        DynamicDataSourceHolder.setDataSourceType(String.valueOf(DataSourceContant.PERSON_DATASOURCE_ID));
        resultMap.put("person", this.personRepository.findById(1).orElse(null));

        logger.info("=====操作DbInfo所在的数据库=====");
        DynamicDataSourceHolder.setDataSourceType(DataSourceContant.DEFAULT_DATASOURCE);
        resultMap.put("dbInfo", this.dbInfoRepository.findById(1).orElse(null));

        return resultMap;
    }
}
